jQuery.comet = {
    fetching: false,
    settings: {},
    url: '',
    bound: {},
    connect: function(url, options) {
        jQuery.comet.settings = jQuery.extend({
            timeout: 60000,
            successTimeInterval: 20000,
            errorTimeInterval: 20000,
            onError: null,
            requestMethod: 'GET',
            dataType: 'json'
        }, options);
        jQuery.comet.url = url;
        jQuery.comet.fetch();
    },

    fetch: function() {
        if (jQuery.comet.fetching)
            return;
        var data = {};
        data.random = Math.random();
        jQuery.comet.fetching = true;
        $.ajax({
            type: jQuery.comet.settings.requestMethod,
            url: jQuery.comet.url,
            dataType: jQuery.comet.settings.dataType,
            data:data,
            async: true,
            cache: true,
            timeout: jQuery.comet.settings.timeout,
            ifModified: true,
            success: function(data) {
                jQuery.comet.fetching = false;
                jQuery.comet.settings.success(data);
                setTimeout(jQuery.comet.fetch, jQuery.comet.settings.successTimeInterval);
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                jQuery.comet.fetching = false;
                if (textStatus == 'timeout') {
                    jQuery.comet.fetch()
                } else {
                    if (jQuery.comet.settings.onError != null) {
                        jQuery.comet.settings.onError(XMLHttpRequest, textStatus, errorThrown);
                    }
                    setTimeout(jQuery.comet.fetch,jQuery.comet.settings.errorTimeInterval);
                }
            }
        });
    }
};
